<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>智能生成课件/笔记</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="goBack">返回列表</el-button>
      </div>
      
      <!-- 生成表单 -->
      <el-form ref="generateForm" :model="generateForm" :rules="rules" label-width="120px" v-loading="loading">
        <el-form-item label="标题" prop="title">
          <el-input v-model="generateForm.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        
        <el-form-item label="类型" prop="type">
          <el-select v-model="generateForm.type" placeholder="请选择类型">
            <el-option :key="1" label="课件" :value="1" />
            <el-option :key="2" label="笔记" :value="2" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="学科" prop="subjectId">
          <el-select v-model="generateForm.subjectId" placeholder="请选择学科" filterable>
            <el-option
              v-for="item in subjectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="教育阶段" prop="educationLevel">
          <el-select v-model="generateForm.educationLevel" placeholder="请选择教育阶段" @change="handleEducationLevelChange">
            <el-option label="小学" :value="1"></el-option>
            <el-option label="初中" :value="2"></el-option>
            <el-option label="高中" :value="3"></el-option>
            <el-option label="大学" :value="4"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="学校" prop="schoolId">
          <el-select v-model="generateForm.schoolId" placeholder="请选择学校（不选则所有学校可见）" filterable clearable>
            <el-option
              v-for="item in schoolOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="关键词/主题" prop="keywords">
          <el-input v-model="generateForm.keywords" placeholder="请输入关键词或主题，例如：面向对象编程,继承与多态"></el-input>
        </el-form-item>
        
        <el-form-item label="详细描述" prop="description">
          <el-input 
            type="textarea" 
            :rows="3" 
            v-model="generateForm.description" 
            placeholder="请输入详细描述，说明内容的主要目的和期望包含的知识点"
          ></el-input>
        </el-form-item>
        
        <el-form-item label="内容长度" prop="contentLength">
          <el-radio-group v-model="generateForm.contentLength">
            <el-radio :label="1">简短</el-radio>
            <el-radio :label="2">适中</el-radio>
            <el-radio :label="3">详细</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="AI提示词">
          <el-input
            type="textarea"
            v-model="generateForm.prompt"
            :rows="3"
            placeholder="可以输入额外的指导提示，例如：希望内容侧重实践应用，包含具体的代码示例">
          </el-input>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">生成内容</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 生成结果弹窗 -->
    <el-dialog 
      title="内容生成结果" 
      :visible.sync="resultDialogVisible"
      width="600px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="generationComplete">
      <div class="generation-result">
        <div v-if="!generationComplete" class="generating">
          <el-progress type="circle" :percentage="generationProgress" :status="generationProgress >= 100 ? 'success' : ''"></el-progress>
          <p class="status-text">{{ generationStatusText }}</p>
        </div>
        <div v-else class="generation-complete">
          <i class="el-icon-success success-icon"></i>
          <h3>内容生成成功</h3>
          <p>标题：{{ generateForm.title }}</p>
          <p>类型：{{ generateForm.type === 1 ? '课件' : '笔记' }}</p>
          <div class="action-buttons">
            <el-button type="primary" @click="viewContent">查看内容</el-button>
            <el-button @click="closeResultDialog">继续创建</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { generateAIMaterial } from '@/api/material';
import { getAllSubjects } from '@/api/subject';
import { getAllSchools } from '@/api/school';

export default {
  name: 'AIMaterialGenerate',
  data() {
    return {
      // 生成表单
      generateForm: {
        title: '',
        type: 1, // 默认课件
        subjectId: undefined,
        educationLevel: undefined,
        schoolId: undefined,
        keywords: '',
        description: '',
        contentLength: 2, // 默认适中
        prompt: ''
      },
      // 表单验证规则
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ],
        subjectId: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        educationLevel: [
          { required: true, message: '请选择教育阶段', trigger: 'change' }
        ]
      },
      // 学科选项
      subjectOptions: [],
      // 所有学科
      allSubjects: [],
      // 学校选项
      schoolOptions: [],
      // 加载状态
      loading: false,
      // 提交状态
      submitLoading: false,
      // 结果对话框
      resultDialogVisible: false,
      // 生成是否完成
      generationComplete: false,
      // 生成进度
      generationProgress: 0,
      // 生成状态文本
      generationStatusText: '正在准备生成...',
      // 生成结果
      generationResult: null,
      // 定时器id
      progressTimer: null
    };
  },
  created() {
    this.getSubjects();
    this.getSchools();
  },
  beforeDestroy() {
    if (this.progressTimer) {
      clearInterval(this.progressTimer);
    }
  },
  methods: {
    // 获取学科列表
    getSubjects() {
      this.loading = true;
      getAllSubjects().then(response => {
        const subjects = response.data || [];
        this.allSubjects = subjects;
        
        // 初始化时显示所有学科或根据已选教育阶段过滤
        if (this.generateForm.educationLevel) {
          this.filterSubjectsByLevel(this.generateForm.educationLevel);
        } else {
          this.subjectOptions = subjects.map(subject => ({
            value: subject.id,
            label: subject.name
          }));
        }
        
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    
    // 获取学校列表
    getSchools() {
      getAllSchools().then(response => {
        const schools = response.data || [];
        this.schoolOptions = schools.map(school => ({
          value: school.id,
          label: school.name
        }));
      });
    },
    
    // 根据教育阶段筛选学科
    filterSubjectsByLevel(level) {
      if (!level || !this.allSubjects || this.allSubjects.length === 0) {
        return;
      }

      const filteredSubjects = this.allSubjects.filter(subject => subject.level === level);
      this.subjectOptions = filteredSubjects.map(subject => ({
        value: subject.id,
        label: subject.name
      }));
      
      // 如果当前选中的学科不在筛选结果中，清空选择
      if (this.generateForm.subjectId) {
        const exists = filteredSubjects.some(subject => subject.id === this.generateForm.subjectId);
        if (!exists) {
          this.generateForm.subjectId = undefined;
        }
      }
    },
    
    // 教育阶段变化时的处理逻辑
    handleEducationLevelChange(level) {
      this.filterSubjectsByLevel(level);
    },
    
    // 提交表单
    submitForm() {
      this.$refs.generateForm.validate(valid => {
        if (valid) {
          this.submitLoading = true;
          this.showGenerationDialog();
          
          // 调用API生成内容
          generateAIMaterial(this.generateForm).then(response => {
            this.submitLoading = false;
            this.generationComplete = true;
            this.generationProgress = 100;
            this.generationResult = response.data;
            this.generationStatusText = '内容生成成功！';
            
            // 清除进度定时器
            if (this.progressTimer) {
              clearInterval(this.progressTimer);
            }
            
            console.log('生成的内容ID:', this.generationResult ? this.generationResult.id : 'undefined');
          }).catch(error => {
            this.submitLoading = false;
            this.generationComplete = true;
            this.generationStatusText = '内容生成失败：' + (error.message || '未知错误');
            
            // 清除进度定时器
            if (this.progressTimer) {
              clearInterval(this.progressTimer);
            }
          });
        }
      });
    },
    
    // 显示生成对话框
    showGenerationDialog() {
      this.resultDialogVisible = true;
      this.generationComplete = false;
      this.generationProgress = 0;
      this.generationStatusText = '正在准备生成...';
      
      // 模拟进度
      this.progressTimer = setInterval(() => {
        if (this.generationProgress < 95) {
          const increment = Math.random() * 5 + 1;
          this.generationProgress = Math.min(95, this.generationProgress + increment);
          
          // 更新状态文本
          if (this.generationProgress < 20) {
            this.generationStatusText = '正在分析学科知识体系...';
          } else if (this.generationProgress < 40) {
            this.generationStatusText = '正在收集相关资料...';
          } else if (this.generationProgress < 70) {
            this.generationStatusText = '正在组织内容结构...';
          } else {
            this.generationStatusText = '正在生成最终内容...';
          }
        }
      }, 800);
    },
    
    // 关闭结果对话框
    closeResultDialog() {
      this.resultDialogVisible = false;
    },
    
    // 查看生成的内容
    viewContent() {
      const contentId = this.generationResult ? this.generationResult.id : null;
      if (contentId) {
        this.$router.push(`/material/detail/${contentId}`);
      } else {
        this.$message.error('内容ID不存在，无法查看');
      }
    },
    
    // 重置表单
    resetForm() {
      this.$refs.generateForm.resetFields();
      this.generateForm.type = 1;
      this.generateForm.contentLength = 2;
    },
    
    // 返回列表
    goBack() {
      this.$router.push('/materials');
    }
  }
};
</script>

<style scoped>
.generating {
  text-align: center;
  padding: 20px 0;
}

.status-text {
  margin-top: 15px;
  color: #606266;
}

.generation-complete {
  text-align: center;
  padding: 20px 0;
}

.success-icon {
  font-size: 48px;
  color: #67C23A;
}

.action-buttons {
  margin-top: 20px;
}
</style> 